package cn.xshi.iot.live.timer;

import cn.xshi.iot.live.util.CacheUtil;
import cn.xshi.iot.live.model.CameraEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.Timer;
import java.util.TimerTask;
/**
 * @Desc 定时任务（杀进程使用,针对回放和直播流停止使用）
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
public class AutoKillTask implements CommandLineRunner {

	private final static Logger logger = LoggerFactory.getLogger(AutoKillTask.class);

	public static Timer timer;

	@Override
	public void run(String... args) throws Exception {
		timer = new Timer("timeTimer");
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				killTask(null);
			}
		}, 1, 1000 * 60);
	}


	public void killTask(String token){
		/*
		logger.info("当前线程总数..."+Thread.getAllStackTraces().keySet().size());
		int nbRunning = 0;
		for (Thread t : Thread.getAllStackTraces().keySet()) {
			if (t.getState()==Thread.State.RUNNABLE){
				logger.info("当前线程运行状况..."+t.getName()+"----"+t.getId());
				nbRunning++;
			}
			logger.info("当前线程运行状况，getName---"+t.getName()+"--getId--"+t.getId()+"--getState--"+t.getState()+"--isAlive--"+t.isAlive()+"--isInterrupted--"+t.isInterrupted());
		}
		*/
		if(StringUtils.isEmpty(token)){
			// 管理缓存
			/*if (null != CacheUtil.STREAMMAP && 0 != CacheUtil.STREAMMAP.size()) {
				//废弃0人访问终止线程
				Set<String> keys = CacheUtil.STREAMMAP.keySet();
				for (String key : keys) {
					// 如果通道使用人数为0，则关闭推流
					if (CacheUtil.STREAMMAP.get(key).getCount() == 0) {
                        // 结束线程
						CameraEntity cameraEntity = CacheUtil.STREAMMAP.get(token);
						cameraEntity.setErrorCount(101);
                        CacheUtil.jobMap.get(key).setInterrupted(cameraEntity);
						logger.info("--------当前无连接，关闭推流器并消耗线程开始-----");
						try {
							PushUtil pushUtil = new PushUtil();
							pushUtil.release(CacheUtil.STREAMMAP.get(token).getGrabber(),CacheUtil.STREAMMAP.get(token).getRecord());
						}catch (Exception e){
							logger.info("--------删除视频流失败-----"+token);
						}
						// 清除缓存
						CacheUtil.STREAMMAP.remove(key);
						CacheUtil.jobMap.remove(key);
						logger.info("--------当前无连接，关闭推流器并消耗线程完毕-----");
					}
				}
			}*/
		}else{
			if (null != CacheUtil.STREAMMAP && null != CacheUtil.STREAMMAP.get(token)) {
				logger.info("--------删除指定视频流开始-----"+token);
				// 结束线程
				if(null != CacheUtil.jobMap && null != CacheUtil.jobMap.get(token)){
					CameraEntity cameraEntity = CacheUtil.STREAMMAP.get(token);
					try {
						cameraEntity.setErrorCount(101);
						CacheUtil.jobMap.get(token).setInterrupted(cameraEntity);
					}catch (Exception e){
						logger.info("--------终止线程失败-----"+token);
					}
				}
				logger.info("--------删除指定视频流完毕-----"+token);
			}
		}
	}
}
